import {
  Component,
  OnInit,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  ViewChild,
  ElementRef,
  AfterViewInit,
  Input,
  Output,
  OnChanges, SimpleChanges, EventEmitter
} from '@angular/core';

import BScroll from '@better-scroll/core';
import ScrollBar from '@better-scroll/scroll-bar';
import MouseWheel from '@better-scroll/mouse-wheel';

BScroll.use(ScrollBar);
BScroll.use(MouseWheel);

import {Song} from '../../../../../data-types/common.types';

@Component({
  selector: 'app-scroll',
  template: `
    <div class="scroll" #wrapRef>
      <ng-content></ng-content>
    </div>
  `,
  styles: [`.scroll {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }`],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ScrollComponent implements OnInit, AfterViewInit, OnChanges {

  @ViewChild('wrapRef', {static: true}) public wrapRef: ElementRef;

  @Input() refreshDelay = 50;

  @Input() songList: Array<Song>;

  @Output() private scrollEndEvent = new EventEmitter<string>();

  private bs: BScroll;

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    this.bs = new BScroll(this.wrapRef.nativeElement, {
      scrollbar: {
        interactive: true
      },
      mouseWheel: {}
    });
    this.bs.on('scrollEnd', (e) => {
      this.scrollEndEvent.emit(e.y);
    });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.songList) {
      this.refreshScroll();
    }
  }

  private refresh() {
    this.bs.refresh();
  }

  public refreshScroll() {
    setTimeout(() => {
      this.refresh();
    }, this.refreshDelay);
  }

  public scrollToElement(...args) {
    this.bs.scrollToElement.apply(this.bs, ...args);
  }
}
